// 案件数据服务类
import { CaseModel, CaseStatus } from '../model/CaseModel';
import { FileIOMock } from '../../mocks/fileioMock';

export class CaseService {
  private static readonly FILE_PATH = 'cases.json';
  
  /**
   * 获取所有案件
   * @returns 案件列表
   */
  public static async getAllCases(): Promise<CaseModel[]> {
    try {
      const cases = await FileIOMock.readJSONFile(this.FILE_PATH);
      return cases.map((item: any) => CaseModel.fromJson(item));
    } catch (error) {
      console.error('Failed to get all cases:', error);
      return [];
    }
  }
  
  /**
   * 根据ID获取案件
   * @param id 案件ID
   * @returns 案件对象，如果不存在返回null
   */
  public static async getCaseById(id: string): Promise<CaseModel | null> {
    try {
      const cases = await this.getAllCases();
      const caseItem = cases.find(item => item.getId() === id);
      return caseItem || null;
    } catch (error) {
      console.error(`Failed to get case by id ${id}:`, error);
      return null;
    }
  }
  
  /**
   * 添加新案件
   * @param caseModel 案件对象
   * @returns 是否添加成功
   */
  public static async addCase(caseModel: CaseModel): Promise<boolean> {
    try {
      // 设置唯一ID
      if (!caseModel.getId()) {
        caseModel.setId(CaseModel.generateId());
      }
      
      const cases = await this.getAllCases();
      cases.push(caseModel);
      
      // 将所有案件对象转换为JSON并保存
      const casesJson = cases.map(item => item.toJson());
      return await FileIOMock.writeJSONFile(this.FILE_PATH, casesJson);
    } catch (error) {
      console.error('Failed to add case:', error);
      return false;
    }
  }
  
  /**
   * 更新案件
   * @param caseModel 更新后的案件对象
   * @returns 是否更新成功
   */
  public static async updateCase(caseModel: CaseModel): Promise<boolean> {
    try {
      const cases = await this.getAllCases();
      const index = cases.findIndex(item => item.getId() === caseModel.getId());
      
      if (index === -1) {
        return false; // 案件不存在
      }
      
      // 更新案件
      cases[index] = caseModel;
      
      // 将所有案件对象转换为JSON并保存
      const casesJson = cases.map(item => item.toJson());
      return await FileIOMock.writeJSONFile(this.FILE_PATH, casesJson);
    } catch (error) {
      console.error(`Failed to update case ${caseModel.getId()}:`, error);
      return false;
    }
  }
  
  /**
   * 删除案件
   * @param id 案件ID
   * @returns 是否删除成功
   */
  public static async deleteCase(id: string): Promise<boolean> {
    try {
      const cases = await this.getAllCases();
      const filteredCases = cases.filter(item => item.getId() !== id);
      
      if (filteredCases.length === cases.length) {
        return false; // 案件不存在
      }
      
      // 将过滤后的案件对象转换为JSON并保存
      const casesJson = filteredCases.map(item => item.toJson());
      return await FileIOMock.writeJSONFile(this.FILE_PATH, casesJson);
    } catch (error) {
      console.error(`Failed to delete case ${id}:`, error);
      return false;
    }
  }
  
  /**
   * 根据状态获取案件
   * @param status 案件状态
   * @returns 符合条件的案件列表
   */
  public static async getCasesByStatus(status: CaseStatus): Promise<CaseModel[]> {
    try {
      const cases = await this.getAllCases();
      return cases.filter(item => item.getStatus() === status);
    } catch (error) {
      console.error(`Failed to get cases by status ${status}:`, error);
      return [];
    }
  }
  
  /**
   * 根据创建人获取案件
   * @param userId 用户ID
   * @returns 符合条件的案件列表
   */
  public static async getCasesByCreator(userId: string): Promise<CaseModel[]> {
    try {
      const cases = await this.getAllCases();
      return cases.filter(item => item.getCreateBy() === userId);
    } catch (error) {
      console.error(`Failed to get cases by creator ${userId}:`, error);
      return [];
    }
  }
  
  /**
   * 搜索案件
   * @param keyword 搜索关键词
   * @returns 符合条件的案件列表
   */
  public static async searchCases(keyword: string): Promise<CaseModel[]> {
    try {
      const cases = await this.getAllCases();
      const lowerKeyword = keyword.toLowerCase();
      
      return cases.filter(item => 
        item.getTitle().toLowerCase().includes(lowerKeyword) ||
        item.getDescription().toLowerCase().includes(lowerKeyword)
      );
    } catch (error) {
      console.error(`Failed to search cases with keyword ${keyword}:`, error);
      return [];
    }
  }
}